package middleware

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"k8s-dash/utils"
	"net/http"
)

type ResponseCode int
type Response struct {
	Code ResponseCode `json:"code"`
	Msg  string       `json:"msg"`
	Data interface{}  `json:"data"`
}

func ResponseSuccess(ctx *gin.Context, data interface{}) {
	//首先将传递过来的的数据实例化
	resp := &Response{Code: http.StatusOK, Msg: "success", Data: data}
	//数据转换
	tmpMsg, ok := data.(string)
	//如果传递数据是空，单独设置msg
	if ok && tmpMsg == "" {
		resp.Msg = "操作成功"
	}
	//这里已经将数据传递了
	ctx.JSON(200, resp)
	response, _ := json.Marshal(resp)
	//这里将数据lazy存储再键值对中给前端使用
	ctx.Set("response", string(response))
}

func ResponseError(ctx *gin.Context, err error) {
	//首先判断错误
	var code ResponseCode
	var realError = new(utils.GlobalError)
	if errors.As(err, &realError) {
		code = ResponseCode(realError.Code)
	}
	resp := &Response{
		Code: code,
		Msg:  err.Error(),
		Data: "",
	}
	ctx.JSON(200, resp)
	response, _ := json.Marshal(resp)
	ctx.Set("response", string(response))
}
